package org.jix.gbook.gateway.auth;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.dev33.satoken.SaManager.log;

/**
 * @author stark
 * @date 2025/5/28 9:26
 * @description
 **/
@Configuration
@Slf4j
public class SaTokenConfigure {
    //注册sa-token全局过滤器
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                //拦截地址
                .addInclude("/**") /*拦截全部path*/
                //鉴权方法
                .setAuth(obj -> {
                    log.info("==================> SaReactorFilter, Path: {}", SaHolder.getRequest().getRequestPath());
                    //登录校验 拦截所有路由，排除/user/doLogin 用于开放登录
                    SaRouter.match("/**") // 拦截所有路由
                            .notMatch("/auth/login") // 排除登录接口
                            .notMatch("/auth/verification/code/send") // 排除验证码发送接口
                            .check(r -> StpUtil.checkLogin()) // 校验是否登录
                    ;
                    /*//权限认证 - 不同模块校验不同权限
                    SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
                    SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
                    SaRouter.match("/goods/**", r -> StpUtil.checkPermission("goods"));
                    SaRouter.match("/orders/**", r -> StpUtil.checkPermission("orders"));*/

//                    SaRouter.match("/auth/user/logout",r -> StpUtil.checkPermission("user"));
                    SaRouter.match("/auth/logout", r -> StpUtil.checkPermission("app:note:publish"));
                    //更多匹配
                })
                .setError(e -> {
                    //手动抛出异常
                    if (e instanceof NotLoginException){
                        //未登录异常
                        throw new NotLoginException(e.getMessage(),null,null);
                    }else if (e instanceof NotPermissionException || e instanceof NotRoleException){
                        // 权限不足，或不具备角色，统一抛出权限不足异常
                        throw new NotPermissionException(e.getMessage());
                    }else {
                        //其他异常，抛出runtimeException
                        throw new RuntimeException(e.getMessage());
                    }
                });
    }
}
